package com.xj.socket.tcp.nio.server;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;

/**
 * 采用nio实现socket的服务端程序
 * <p/>
 * 日期 2013-02-22
 * 
 * @author xiajun
 * 
 */
public class SocketServer {
	private final static Logger log = Logger.getLogger(SocketServer.class);
	private ServerSocketChannel ssc = null;
	private ServerSocket socket = null;
	private String ip = null;
	private int port;
	private ConnectionSelector cs = null;

	/**
	 * 默认构造函数 IP：0.0.0.0 　PORT： 6188　
	 */
	public SocketServer() {
		this("0.0.0.0", 6188);
	}

	/**
	 * 构造SocketServer
	 * 
	 * @param ip
	 *            socket 使用的IP地址
	 * @param port
	 *            socket 使用的端口号
	 */
	public SocketServer(String ip, int port) {
		this.port = port;
		this.ip = ip;
	}

	/**
	 * 初始化ServerSocketChannel
	 * 
	 * @throws java.io.IOException
	 */
	private void init() throws IOException {
		this.ssc = ServerSocketChannel.open();
		this.ssc.configureBlocking(false);
		this.socket = this.ssc.socket();
		this.socket.bind(new InetSocketAddress(ip, port));
		cs = new ConnectionSelector();
		log.info("服务开启成功...");
	}

	/**
	 * 开启socket服务 并监听使用连接选择器 进行监听连接事件 ConnectionSelector
	 *
	 * @throws java.io.IOException
	 */
	public void start() throws IOException {
		this.init();
		this.ssc.register(cs.getSelector(), SelectionKey.OP_ACCEPT);
		log.debug("开始监听客户端连接...");
		new Thread(cs).start();
	}

	public static void main(String[] args) {
		SocketServer s = new SocketServer();
		try {
			s.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
